package com.lx.controller;

import com.lx.bean.Message;
import com.lx.mvc.ResponseBody;
import com.lx.service.AdminService;
import com.lx.service.imp.AdminServiceImpl;
import com.lx.util.ApplicationUtil;
import com.lx.util.JsonUtil;
import org.springframework.context.ApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @ClassName: AdminCtroller
 * @Description:
 * @Date Created in  2021-07-06 17:21
 * @Modified By:
 * @Author: 零巽
 */
public class AdminController {
    private AdminService adminService = new AdminServiceImpl();
    ApplicationContext applicationContext = ApplicationUtil.loadApplicationContext();

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        //接受参数
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        //调用Service传递参数并获取结果
        boolean result = adminService.login(userName, password);
        //根据结果返回数据给AJAX
        Message message =null;
        if (result) {
            message = new Message(0, "登录成功");
            //更新登录时间和ip
            Date date = new Date();
            String ip = req.getRemoteAddr();
            adminService.updateLoginTimeAndIp(userName,date,ip);
            //存储用户名到session
            HttpSession session = req.getSession();
            session.setAttribute("adminUserName",userName);
        } else {
            message = new Message(-1, "登录失败");
        }
        //将数据转换为Json对象并返回给Ajax
        return JsonUtil.toJSON(message);
    }

    @ResponseBody("/admin/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse response) {
        HttpSession session = req.getSession();//获取session对象
        session.invalidate();//清空session内容
//        Message message = new Message();
        //替换原来创建Bean类的方式

        Message message = (Message) applicationContext.getBean("message");
        message.setResult("成功退出！");
        return JsonUtil.toJSON(message);
    }
}
